package com.sweetest.luffy.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sweetest.luffy.config.WebSocket;
import com.sweetest.luffy.entity.Message;
import com.sweetest.luffy.entity.User;
import com.sweetest.luffy.page.Result;
import com.sweetest.luffy.service.IMessageService;
import com.sweetest.luffy.service.IUserService;
import com.sweetest.luffy.util.JwtUtil;
import com.sweetest.luffy.vo.MessageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/message")
@Api(tags = "消息")
public class MessageController {

    @Resource
    IMessageService messageService;
    @Resource
    WebSocket webSocket;
    @Resource
    IUserService userService;

    @GetMapping(value = "/getMessage")
    @ApiOperation(value = "获取消息对话")
    public Result<Object> getMessage(HttpServletRequest request, Integer userId, Integer status) {
        Integer id = JwtUtil.getUserId(request);
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or(e -> e.eq(Message::getSendUserId, id).eq(Message::getReceiveUserId, userId));
        queryWrapper.or(e -> e.eq(Message::getSendUserId, userId).eq(Message::getReceiveUserId, id));
//        queryWrapper.eq(Message::getSendUserId, id).or().eq(Message::getReceiveUserId,userId);
//        queryWrapper.eq(Message::getReceiveUserId, userId).or().eq(Message::getSendUserId,id);
        if (null != status) {
            queryWrapper.eq(Message::getStatus, status);
        }
        List<Message> messageList = messageService.list(queryWrapper);
        List<MessageVo> messageVoList = new ArrayList<>();
        for (Message mess : messageList) {
            mess.setStatus(1);
            messageService.updateById(mess);
            messageVoList.add(messageToVo(mess));
        }
        return Result.ok(messageVoList);
    }

    @PostMapping(value = "/sendMessage")
    @ApiOperation(value = "发送信息")
    public Result<Object> sendMessage(HttpServletRequest request, @RequestBody Message message) {
        Integer id = JwtUtil.getUserId(request);
        message.setCreateDate(new Date());
        message.setSendUserId(id);
        MessageVo vo = messageToVo(message);
        boolean flag = webSocket.sendOneMessage(message.getReceiveUserId() + "", JSONObject.toJSONString(vo));
        if (flag) {
            message.setStatus(1);
        } else {
            message.setStatus(0);
        }
        messageService.save(message);
        return Result.ok(vo);
    }

    @GetMapping(value = "/getMessageList")
    @ApiOperation(value = "用户消息列表")
    public Result<List<MessageVo>> getMessageList(HttpServletRequest request) {
        Integer id = JwtUtil.getUserId(request);
        Result<List<MessageVo>> result = new Result<>();
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.last(" where create_date in (select MAX(create_date) from m_message where send_user_id = " + id + " OR receive_user_id = " + id +
                "  GROUP BY CONCAT( IF ( send_user_id > receive_user_id, send_user_id, receive_user_id ), IF ( send_user_id < receive_user_id, send_user_id, receive_user_id  ))) ORDER BY create_date DESC  ");
        List<Message> list = messageService.list(queryWrapper);
        List<MessageVo> messageVoList = list.stream().map(this::messageToVo).collect(Collectors.toList());
        result.setData(messageVoList);
        return result;
    }


    private MessageVo messageToVo(Message message) {
        MessageVo vo = new MessageVo();
        BeanUtil.copyProperties(message, vo);
        User send = userService.getById(message.getSendUserId());
        User receive = userService.getById(message.getReceiveUserId());
        vo.setReceiveUserFirst(receive.getFirstName());
        vo.setReceiveUserLast(receive.getLastName());
        vo.setSendUserFirst(send.getFirstName());
        vo.setSendUserLast(send.getLastName());
        return vo;
    }
}
